/**
 * 设备ID生成工具
 * 生成稳定的设备标识，用于多设备登录管理
 */

interface DeviceInfo {
  userAgent: string;
  screenWidth: number;
  screenHeight: number;
  colorDepth: number;
  timezone: string;
  language: string;
  platform: string;
}

/**
 * 获取设备信息
 */
function getDeviceInfo(): DeviceInfo {
  return {
    userAgent: navigator.userAgent,
    screenWidth: screen.width,
    screenHeight: screen.height,
    colorDepth: screen.colorDepth,
    timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    language: navigator.language,
    platform: navigator.platform,
  };
}

/**
 * 生成设备指纹
 */
function generateDeviceFingerprint(): string {
  const deviceInfo = getDeviceInfo();
  
  // 创建设备信息字符串
  const deviceString = [
    deviceInfo.userAgent,
    deviceInfo.screenWidth,
    deviceInfo.screenHeight,
    deviceInfo.colorDepth,
    deviceInfo.timezone,
    deviceInfo.language,
    deviceInfo.platform,
  ].join('|');
  
  // 使用简单的哈希算法生成指纹
  let hash = 0;
  for (let i = 0; i < deviceString.length; i++) {
    const char = deviceString.charCodeAt(i);
    hash = ((hash << 5) - hash) + char;
    hash = hash & hash; // 转换为32位整数
  }
  
  return Math.abs(hash).toString(36);
}

/**
 * 获取或生成设备ID
 * 优先使用本地存储中的设备ID，如果没有则生成新的
 */
export function getOrGenerateDeviceId(): string {
  const storageKey = 'device_id';
  
  // 尝试从本地存储获取设备ID
  let deviceId = localStorage.getItem(storageKey);
  
  if (!deviceId) {
    // 如果没有设备ID，生成一个新的
    deviceId = generateDeviceFingerprint();
    
    // 保存到本地存储
    localStorage.setItem(storageKey, deviceId);
    
    console.log('Generated new device ID:', deviceId);
  }
  
  return deviceId;
}

/**
 * 清除设备ID
 */
export function clearDeviceId(): void {
  localStorage.removeItem('device_id');
}

/**
 * 获取设备信息（用于调试）
 */
export function getDeviceInfoForDebug(): DeviceInfo {
  return getDeviceInfo();
}

/**
 * 检查设备ID是否有效
 */
export function isValidDeviceId(deviceId: string | boolean): boolean {
  return typeof deviceId === 'string' && deviceId.length > 0 && /^[a-z0-9]+$/i.test(deviceId);
}
